# This file is part of the Net::Tube module.
#
# Net::Tube is Free Software; you can use, redistribute it and/or
# modify it under the terms of either:
#
# a) the GNU General Public License as published by the Free Software
#    Foundation, either version 2, or (at your opinion) any later
#    version, or
#
# b) the "Artistic License" which comes with Perl.
#
package Net::Tube::Filter::Limit;

# this filter accepts a number of XPATHS and a limit of maximum elements for
# each XPath. If a bucket has more elements than the limit, this filter will
# remove these nodes.

use Net::Tube;

our @ISA = qw(Net::Tube::Filter);

sub limit {
    my $self = shift;
    my ($limit) = $self->get_config_entry('limit');
    unless ( $limit > 0 ) {
        $limit = 0;
    }
    return $limit;
}

sub elements {
    my $self          = shift;
    my $elemXPathList = $self->get_config_entry('element-filter');
    return $elemXPathList;
}

sub process {
    my $self       = shift;
    my $bucket     = $self->SUPER::process(@_);
    my $limit      = $self->limit();
    my $elemFilter = $self->elements();

    if ( $limit > 0 and scalar @$elemFilter ) {
        foreach my $filter (@$elemFilter) {
            foreach my $n ( @{ $bucket->node_list() } ) {
                my $nodes = $n->findnodes($filter);
                next unless scalar @$nodes > $limit;
                for (
                    my $i = $limit ;
                    $i < scalar(@$nodes) ;
                    $nodes->[ $i++ ]->unbindNode()
                  )
                {
                }
            }    
        }
    }
    return $bucket;
}

1;
